package com.ldfile.server.controller;

import com.ldfile.server.config.FileServiceInfoConfiguration;
import com.ldfile.server.exception.FileServerException;
import com.ldfile.server.response.SimpleResponse;
import com.ldfile.server.utils.FileUploadUtils;
import com.ldfile.server.utils.wechatQRCodeUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * @author callmecool.ldsoft
 * @description tools
 * @since 2020/7/30 15:31
 */
@RequestMapping("/api")
@Controller
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Slf4j
public class FileUploadController {

    private final FileServiceInfoConfiguration fileServiceInfoConfiguration;

    private final FileUploadUtils fileUploadUtils;
    private final wechatQRCodeUtils wechatQRCodeUtils;

    /**
     * 批量上传文件
     */
    @PostMapping("/upload")
    @ResponseBody
    public SimpleResponse save(HttpServletRequest request) {
        log.debug("请求进入");
        SimpleResponse success = SimpleResponse.success(fileUploadUtils.save(request));
        log.debug("请求完成");
        return success;
    }


    @GetMapping("/getUpldateStatus")
    @ResponseBody
    public SimpleResponse getUpldateStatus(HttpServletRequest request) {
        return SimpleResponse.success(request.getSession().getAttribute("status"));
    }

    /**
     * 批量删除文件
     */
    @PostMapping("/del")
    @ResponseBody
    public SimpleResponse del(@RequestParam(value = "urls") List<String> urls) {
        return SimpleResponse.success(fileUploadUtils.del(urls));
    }

    @PostMapping("/buildQRCode")
    @ResponseBody
    public SimpleResponse getQRCokde(@RequestParam String filename, @RequestParam String page, @RequestParam String scene) throws FileServerException {
        String accessToken = wechatQRCodeUtils.getToken();
        return SimpleResponse.success(wechatQRCodeUtils.getminiqrQr(accessToken, filename, page, scene));
    }

    @GetMapping("/getFileTumb/**/{filePath:.+}")
    public void getFileTumb(@PathVariable("filePath") String filePath,
                            @RequestParam("width") Integer width,
                            @RequestParam("height") Integer height,
                            HttpServletRequest request,
                            HttpServletResponse response) {
        String servletPath = request.getServletPath();
        File srcfile = new File(String.format("%s/%s", fileServiceInfoConfiguration.getDirYml(), servletPath.replaceFirst("/api/getFileTumb/", "")));
        if (!srcfile.exists()) {
            response.setStatus(404);
            return;
        }
        File descFile = new File(String.format("%s/%s_%s_%s.jpg", fileServiceInfoConfiguration.getDirYml(), servletPath.replaceFirst("/api/getFileTumb/", ""), width, height));
        if (!descFile.exists()) {
            try {
                Thumbnails.of(srcfile).size(width, height).toFile(descFile);
            } catch (IOException e) {

            }
        }
        response.setContentType("image/jpeg");
        FileInputStream fileInputStream = null;
        OutputStream outputStream = null;
        try {
            fileInputStream = new FileInputStream(descFile);
            outputStream = response.getOutputStream();
            response.setContentLength((int) descFile.length());

            byte[] byts = new byte[1024];
            int l = 0;
            while ((l = fileInputStream.read(byts)) > 0) {
                outputStream.write(byts, 0, l);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    //
                }
            }
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    //
                }
            }
        }
    }
}
